package com.example.socialapp.ui.social

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Chip
import androidx.compose.material.ChipDefaults
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.Group
import androidx.compose.material.icons.filled.Help
import androidx.compose.material.icons.filled.People
import androidx.compose.material.icons.filled.PersonAdd
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.zIndex
import kotlin.math.absoluteValue
import kotlin.math.cos
import kotlin.math.sin
import kotlin.random.Random

/**
 * 社交关系图界面
 *
 * @param userId 用户ID
 * @param onNavigateBack 返回上一界面回调
 * @param onNavigateToUserProfile 导航到用户资料界面回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SocialGraphScreen(
    userId: String = "",
    onNavigateBack: () -> Unit,
    onNavigateToUserProfile: (String) -> Unit = {}
) {
    // 在实际应用中应从ViewModel获取用户关系数据
    val userGraph = remember { generateSampleUserGraph(userId) }
    
    // 图表控制状态
    var scale by remember { mutableFloatStateOf(1f) }
    var offset by remember { mutableStateOf(Offset.Zero) }
    var selectedRelationType by remember { mutableStateOf(RelationType.ALL) }
    var showHelpDialog by remember { mutableStateOf(false) }
    var selectedUser by remember { mutableStateOf<UserNode?>(null) }
    var animationProgress by remember { mutableFloatStateOf(0f) }
    
    // 动画效果
    val animatedProgress by animateFloatAsState(
        targetValue = animationProgress,
        animationSpec = tween(1500),
        label = "graphAnimation"
    )
    
    // 启动入场动画
    LaunchedEffect(Unit) {
        animationProgress = 1f
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("社交关系图") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { /* 分享社交图 */ }) {
                        Icon(
                            imageVector = Icons.Default.Share,
                            contentDescription = "分享"
                        )
                    }
                    IconButton(onClick = { showHelpDialog = true }) {
                        Icon(
                            imageVector = Icons.Default.Help,
                            contentDescription = "帮助"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            // 关系类型过滤器
            RelationTypeFilter(
                selectedType = selectedRelationType,
                onTypeSelected = { selectedRelationType = it }
            )
            
            // 图表控制
            GraphControlPanel(
                scale = scale,
                onScaleChange = { scale = it }
            )
            
            // 社交关系图
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .padding(16.dp)
                    .pointerInput(Unit) {
                        detectTransformGestures { _, pan, zoom, _ ->
                            scale = (scale * zoom).coerceIn(0.5f, 2.5f)
                            offset += pan
                        }
                    }
            ) {
                // 绘制关系图
                SocialGraph(
                    userGraph = userGraph,
                    scale = scale,
                    offset = offset,
                    animationProgress = animatedProgress,
                    selectedRelationType = selectedRelationType,
                    onUserNodeClick = { 
                        selectedUser = it
                        onNavigateToUserProfile(it.id)
                    }
                )
            }
            
            // 推荐连接
            SuggestedConnectionsSection(
                suggestedConnections = userGraph.suggestedConnections,
                onUserClick = { onNavigateToUserProfile(it.id) }
            )
        }
    }
    
    // 帮助对话框
    if (showHelpDialog) {
        HelpDialog(onDismiss = { showHelpDialog = false })
    }
    
    // 用户详情弹窗
    selectedUser?.let { user ->
        UserDetailsPopup(
            user = user,
            onDismiss = { selectedUser = null },
            onViewProfile = { onNavigateToUserProfile(user.id) }
        )
    }
}

/**
 * 关系类型过滤器
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun RelationTypeFilter(
    selectedType: RelationType,
    onTypeSelected: (RelationType) -> Unit
) {
    val relationTypes = RelationType.values()
    
    LazyRow(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(relationTypes) { type ->
            FilterChip(
                selected = selectedType == type,
                onClick = { onTypeSelected(type) },
                label = { Text(type.displayName) },
                leadingIcon = {
                    Icon(
                        imageVector = when (type) {
                            RelationType.ALL -> Icons.Default.Group
                            RelationType.FRIENDS -> Icons.Default.People
                            RelationType.FOLLOWING -> Icons.Default.AccountCircle
                            RelationType.SUGGESTED -> Icons.Default.PersonAdd
                        },
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                }
            )
        }
    }
}

/**
 * 图表控制面板
 */
@Composable
private fun GraphControlPanel(
    scale: Float,
    onScaleChange: (Float) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = Icons.Default.FilterList,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.primary
        )
        
        Spacer(modifier = Modifier.width(8.dp))
        
        Text(
            text = "缩放",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurface
        )
        
        Slider(
            value = scale,
            onValueChange = onScaleChange,
            valueRange = 0.5f..2.5f,
            modifier = Modifier.weight(1f)
        )
    }
}

/**
 * 社交关系图
 */
@Composable
private fun SocialGraph(
    userGraph: UserGraph,
    scale: Float,
    offset: Offset,
    animationProgress: Float,
    selectedRelationType: RelationType,
    onUserNodeClick: (UserNode) -> Unit
) {
    // Get colors outside the Canvas scope
    val primaryColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.8f)
    
    Canvas(modifier = Modifier.fillMaxSize()) {
        val centerX = size.width / 2 + offset.x
        val centerY = size.height / 2 + offset.y
        val radius = minOf(size.width, size.height) / 3f * scale * animationProgress
        
        // 绘制所有连接
        userGraph.connections.forEach { connection ->
            // 根据选中的关系类型过滤
            if (selectedRelationType == RelationType.ALL || 
                (selectedRelationType == RelationType.FRIENDS && connection.type == ConnectionType.FRIEND) ||
                (selectedRelationType == RelationType.FOLLOWING && connection.type == ConnectionType.FOLLOWING)
            ) {
                // 计算两个节点的位置
                val fromNode = userGraph.nodes.find { it.id == connection.fromUserId }
                val toNode = userGraph.nodes.find { it.id == connection.toUserId }
                
                if (fromNode != null && toNode != null) {
                    val fromAngle = fromNode.angle * animationProgress
                    val toAngle = toNode.angle * animationProgress
                    
                    val fromX = centerX + cos(fromAngle) * radius * fromNode.distanceFactor
                    val fromY = centerY + sin(fromAngle) * radius * fromNode.distanceFactor
                    val toX = centerX + cos(toAngle) * radius * toNode.distanceFactor
                    val toY = centerY + sin(toAngle) * radius * toNode.distanceFactor
                    
                    // 绘制连接线
                    drawLine(
                        color = when (connection.type) {
                            ConnectionType.FRIEND -> Color(0xFF4CAF50)
                            ConnectionType.FOLLOWING -> Color(0xFF2196F3)
                        },
                        start = Offset(fromX, fromY),
                        end = Offset(toX, toY),
                        strokeWidth = 2f * scale,
                        alpha = 0.6f * animationProgress
                    )
                }
            }
        }
        
        // 绘制所有节点
        userGraph.nodes.forEach { node ->
            // 根据选中的关系类型过滤
            val shouldShow = when (selectedRelationType) {
                RelationType.ALL -> true
                RelationType.FRIENDS -> userGraph.connections.any { 
                    (it.fromUserId == node.id || it.toUserId == node.id) && it.type == ConnectionType.FRIEND 
                }
                RelationType.FOLLOWING -> userGraph.connections.any { 
                    (it.fromUserId == node.id || it.toUserId == node.id) && it.type == ConnectionType.FOLLOWING 
                }
                RelationType.SUGGESTED -> node.id in userGraph.suggestedConnections.map { it.id }
            }
            
            if (shouldShow) {
                val angle = node.angle * animationProgress
                val x = centerX + cos(angle) * radius * node.distanceFactor
                val y = centerY + sin(angle) * radius * node.distanceFactor
                
                // 确定节点是否为当前用户
                val isCurrentUser = node.id == userGraph.currentUserId
                val nodeRadius = if (isCurrentUser) 30f * scale else 20f * scale
                
                // 绘制节点
                drawCircle(
                    color = if (isCurrentUser) primaryColor 
                           else getColorForName(node.name),
                    radius = nodeRadius,
                    center = Offset(x, y),
                    alpha = animationProgress
                )
                
                // 绘制节点边框
                drawCircle(
                    color = Color.White,
                    radius = nodeRadius,
                    center = Offset(x, y),
                    style = Stroke(width = 2f * scale),
                    alpha = 0.8f * animationProgress
                )
                
                // 添加点击区域
                if (isPointInCircle(Offset(x, y), nodeRadius, Offset.Zero)) {
                    onUserNodeClick(node)
                }
            }
        }
    }
    
    // 绘制节点标签
    BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
        val boxWidth = constraints.maxWidth.toFloat()
        val boxHeight = constraints.maxHeight.toFloat()
        
        userGraph.nodes.forEach { node ->
            // 根据选中的关系类型过滤
            val shouldShow = when (selectedRelationType) {
                RelationType.ALL -> true
                RelationType.FRIENDS -> userGraph.connections.any { 
                    (it.fromUserId == node.id || it.toUserId == node.id) && it.type == ConnectionType.FRIEND 
                }
                RelationType.FOLLOWING -> userGraph.connections.any { 
                    (it.fromUserId == node.id || it.toUserId == node.id) && it.type == ConnectionType.FOLLOWING 
                }
                RelationType.SUGGESTED -> node.id in userGraph.suggestedConnections.map { it.id }
            }
            
            if (shouldShow) {
                val centerX = boxWidth / 2 + offset.x
                val centerY = boxHeight / 2 + offset.y
                val radius = minOf(boxWidth, boxHeight) / 3f * scale * animationProgress
                
                val angle = node.angle * animationProgress
                val x = centerX + cos(angle) * radius * node.distanceFactor
                val y = centerY + sin(angle) * radius * node.distanceFactor
                
                // 确定节点是否为当前用户
                val isCurrentUser = node.id == userGraph.currentUserId
                
                // 创建可点击的用户节点标签
                NodeLabel(
                    name = node.name,
                    isCurrentUser = isCurrentUser,
                    x = x,
                    y = y,
                    scale = scale,
                    animationProgress = animationProgress,
                    onClick = { onUserNodeClick(node) }
                )
            }
        }
    }
}

/**
 * 节点标签
 */
@Composable
private fun NodeLabel(
    name: String,
    isCurrentUser: Boolean,
    x: Float,
    y: Float,
    scale: Float,
    animationProgress: Float,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .offset(x = x.dp, y = (y + 30 * scale).dp)
    ) {
        Text(
            text = name,
            color = if (isCurrentUser) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurface,
            fontSize = (12 * scale).sp,
            fontWeight = if (isCurrentUser) FontWeight.Bold else FontWeight.Normal,
            textAlign = TextAlign.Center,
            modifier = Modifier
                .zIndex(if (isCurrentUser) 10f else 1f)
                .alpha(animationProgress)
                .background(
                    color = if (isCurrentUser) 
                        MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)
                    else 
                        MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.7f),
                    shape = RoundedCornerShape(4.dp)
                )
                .padding(horizontal = 6.dp, vertical = 2.dp)
                .clickable(onClick = onClick)
        )
    }
}

/**
 * 推荐连接部分
 */
@Composable
private fun SuggestedConnectionsSection(
    suggestedConnections: List<UserNode>,
    onUserClick: (UserNode) -> Unit
) {
    if (suggestedConnections.isNotEmpty()) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(
                text = "推荐关注",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.primary
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            LazyRow(
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                items(suggestedConnections) { user ->
                    SuggestedUserItem(
                        user = user,
                        onClick = { onUserClick(user) }
                    )
                }
            }
        }
    }
}

/**
 * 推荐用户项
 */
@Composable
private fun SuggestedUserItem(
    user: UserNode,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .width(140.dp)
            .clickable(onClick = onClick),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier.padding(12.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 用户头像
            Box(
                modifier = Modifier
                    .size(60.dp)
                    .clip(CircleShape)
                    .background(getColorForName(user.name)),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = user.name.first().toString(),
                    color = Color.White,
                    fontSize = 24.sp,
                    fontWeight = FontWeight.Bold
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 用户名
            Text(
                text = user.name,
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Bold,
                maxLines = 1,
                textAlign = TextAlign.Center
            )
            
            // 推荐理由
            Text(
                text = user.recommendReason ?: "可能认识的人",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.outline,
                maxLines = 2,
                textAlign = TextAlign.Center
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 关注按钮
            @OptIn(ExperimentalMaterialApi::class)
            Chip(
                onClick = { /* 关注用户 */ },
                colors = ChipDefaults.chipColors(
                    backgroundColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.8f),
                    contentColor = MaterialTheme.colorScheme.onPrimaryContainer
                ),
                modifier = Modifier.padding(4.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.PersonAdd,
                    contentDescription = null,
                    modifier = Modifier.size(16.dp)
                )
                Spacer(modifier = Modifier.width(4.dp))
                Text("关注")
            }
        }
    }
}

/**
 * 帮助对话框
 */
@Composable
private fun HelpDialog(onDismiss: () -> Unit) {
    Dialog(onDismissRequest = onDismiss) {
        Surface(
            shape = RoundedCornerShape(16.dp),
            color = MaterialTheme.colorScheme.surface
        ) {
            Column(
                modifier = Modifier
                    .padding(24.dp)
                    .fillMaxWidth()
            ) {
                Text(
                    text = "社交关系图帮助",
                    style = MaterialTheme.typography.titleLarge,
                    color = MaterialTheme.colorScheme.primary
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                Text(
                    text = "• 您可以看到您与其他用户的社交关系网络",
                    style = MaterialTheme.typography.bodyMedium
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "• 绿色连线代表互相关注的好友关系",
                    style = MaterialTheme.typography.bodyMedium
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "• 蓝色连线代表单向关注关系",
                    style = MaterialTheme.typography.bodyMedium
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "• 点击用户头像或名称可查看详细资料",
                    style = MaterialTheme.typography.bodyMedium
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "• 使用滑块调整图表大小",
                    style = MaterialTheme.typography.bodyMedium
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "• 使用过滤器查看不同类型的社交关系",
                    style = MaterialTheme.typography.bodyMedium
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End
                ) {
                    @OptIn(ExperimentalMaterialApi::class)
                    Chip(
                        onClick = onDismiss,
                        colors = ChipDefaults.chipColors(
                            backgroundColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        ),
                        modifier = Modifier.padding(4.dp)
                    ) {
                        Text("了解")
                    }
                }
            }
        }
    }
}

/**
 * 用户详情弹窗
 */
@Composable
private fun UserDetailsPopup(
    user: UserNode,
    onDismiss: () -> Unit,
    onViewProfile: () -> Unit
) {
    Dialog(onDismissRequest = onDismiss) {
        Card(
            shape = RoundedCornerShape(16.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Column(
                modifier = Modifier
                    .padding(16.dp)
                    .fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 用户头像
                Box(
                    modifier = Modifier
                        .size(80.dp)
                        .clip(CircleShape)
                        .background(getColorForName(user.name)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = user.name.first().toString(),
                        color = Color.White,
                        fontSize = 32.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
                
                Spacer(modifier = Modifier.height(12.dp))
                
                // 用户名
                Text(
                    text = user.name,
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                // 用户简介
                Text(
                    text = user.bio ?: "这个人很懒，什么都没有留下。",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 用户统计
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(
                            text = "${user.followers}",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = "粉丝",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.outline
                        )
                    }
                    
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(
                            text = "${user.following}",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = "关注",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.outline
                        )
                    }
                    
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(
                            text = "${user.mutualConnections}",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = "共同好友",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.outline
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    @OptIn(ExperimentalMaterialApi::class)
                    Chip(
                        onClick = onViewProfile,
                        colors = ChipDefaults.chipColors(
                            backgroundColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        ),
                        modifier = Modifier.padding(4.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.AccountCircle,
                            contentDescription = null,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text("查看资料")
                    }
                    
                    @OptIn(ExperimentalMaterialApi::class)
                    Chip(
                        onClick = onDismiss,
                        colors = ChipDefaults.chipColors(
                            backgroundColor = MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                        ),
                        modifier = Modifier.padding(4.dp)
                    ) {
                        Text("关闭")
                    }
                }
            }
        }
    }
}

/**
 * 根据名称生成颜色
 */
private fun getColorForName(name: String): Color {
    val colors = listOf(
        Color(0xFF6200EA), // 深紫色
        Color(0xFF2962FF), // 深蓝色
        Color(0xFF00BFA5), // 青色
        Color(0xFFFFAB00), // 琥珀色
        Color(0xFFD50000)  // 红色
    )
    
    return colors[name.hashCode().mod(colors.size).absoluteValue]
}

/**
 * 检查点是否在圆内
 */
private fun isPointInCircle(circleCenter: Offset, radius: Float, point: Offset): Boolean {
    val dx = circleCenter.x - point.x
    val dy = circleCenter.y - point.y
    return dx * dx + dy * dy <= radius * radius
}

/**
 * 关系类型枚举
 */
enum class RelationType(val displayName: String) {
    ALL("全部关系"),
    FRIENDS("互相关注"),
    FOLLOWING("单向关注"),
    SUGGESTED("推荐关注")
}

/**
 * 连接类型枚举
 */
enum class ConnectionType {
    FRIEND,      // 互为好友（双向关注）
    FOLLOWING    // 单向关注
}

/**
 * 用户节点数据类
 */
data class UserNode(
    val id: String,
    val name: String,
    val angle: Float,                // 节点在图中的角度
    val distanceFactor: Float = 1f,  // 节点离中心的距离因子
    val followers: Int = 0,          // 粉丝数
    val following: Int = 0,          // 关注数
    val mutualConnections: Int = 0,  // 共同好友数
    val bio: String? = null,         // 个人简介
    val recommendReason: String? = null  // 推荐理由
)

/**
 * 社交连接数据类
 */
data class SocialConnection(
    val fromUserId: String,
    val toUserId: String,
    val type: ConnectionType
)

/**
 * 用户社交图数据类
 */
data class UserGraph(
    val currentUserId: String,
    val nodes: List<UserNode>,
    val connections: List<SocialConnection>,
    val suggestedConnections: List<UserNode>
)

/**
 * 生成示例用户社交图数据
 */
private fun generateSampleUserGraph(userId: String): UserGraph {
    val random = Random(System.currentTimeMillis())
    
    // 设置当前用户ID
    val currentUserId = userId.ifEmpty { "user-0" }
    
    // 生成用户节点
    val userNames = listOf("张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十", "郑十一", "钱十二")
    val nodeCount = 12
    
    val nodes = List(nodeCount) { index ->
        val id = if (index == 0) currentUserId else "user-$index"
        val name = if (index < userNames.size) userNames[index] else "用户$index"
        val angle = (index * 2 * Math.PI / nodeCount).toFloat()
        val distanceFactor = if (index == 0) 0f else random.nextFloat() * 0.4f + 0.8f
        
        UserNode(
            id = id,
            name = name,
            angle = angle,
            distanceFactor = distanceFactor,
            followers = random.nextInt(10, 500),
            following = random.nextInt(10, 300),
            mutualConnections = random.nextInt(0, 15),
            bio = if (random.nextBoolean()) {
                listOf(
                    "热爱旅行和摄影，记录生活中的美好时刻。",
                    "美食爱好者，分享各种美食和烹饪秘诀。",
                    "科技爱好者，关注最新科技动态和产品。",
                    "喜欢阅读和写作，分享心得和感悟。",
                    "健身达人，热爱运动和健康生活方式。"
                )[random.nextInt(5)]
            } else null
        )
    }
    
    // 生成社交连接
    val connections = mutableListOf<SocialConnection>()
    
    // 确保当前用户与一些人有连接
    for (i in 1 until minOf(8, nodeCount)) {
        val connectionType = if (i <= 4) ConnectionType.FRIEND else ConnectionType.FOLLOWING
        
        // 根据连接类型添加适当的连接
        if (connectionType == ConnectionType.FRIEND) {
            // 互相关注
            connections.add(SocialConnection(currentUserId, "user-$i", ConnectionType.FOLLOWING))
            connections.add(SocialConnection("user-$i", currentUserId, ConnectionType.FOLLOWING))
        } else {
            // 单向关注
            connections.add(SocialConnection(currentUserId, "user-$i", ConnectionType.FOLLOWING))
        }
    }
    
    // 添加一些随机连接
    val maxConnections = (nodeCount * (nodeCount - 1)) / 4
    val targetConnections = random.nextInt(nodeCount, maxConnections)
    
    while (connections.size < targetConnections) {
        val fromIndex = random.nextInt(1, nodeCount)
        val toIndex = random.nextInt(1, nodeCount)
        
        if (fromIndex != toIndex) {
            val fromId = "user-$fromIndex"
            val toId = "user-$toIndex"
            
            // 避免重复连接
            if (!connections.any { it.fromUserId == fromId && it.toUserId == toId }) {
                val type = if (random.nextBoolean()) ConnectionType.FRIEND else ConnectionType.FOLLOWING
                connections.add(SocialConnection(fromId, toId, type))
                
                // 如果是互相关注，添加反向连接
                if (type == ConnectionType.FRIEND && 
                    !connections.any { it.fromUserId == toId && it.toUserId == fromId }) {
                    connections.add(SocialConnection(toId, fromId, ConnectionType.FOLLOWING))
                }
            }
        }
    }
    
    // 生成推荐关注
    val existingConnections = connections.filter { it.fromUserId == currentUserId }.map { it.toUserId }
    val potentialSuggestions = nodes.filter { it.id != currentUserId && it.id !in existingConnections }
    
    val suggestedConnections = potentialSuggestions.take(minOf(5, potentialSuggestions.size)).map { node ->
        // 为推荐添加理由
        val reasons = listOf(
            "你可能认识的人",
            "与你的3位好友有联系",
            "根据你的兴趣推荐",
            "最近很活跃的用户",
            "${userNames[random.nextInt(userNames.size)]}也关注了Ta"
        )
        
        node.copy(recommendReason = reasons[random.nextInt(reasons.size)])
    }
    
    return UserGraph(
        currentUserId = currentUserId,
        nodes = nodes,
        connections = connections,
        suggestedConnections = suggestedConnections
    )
} 